<!DOCTYPE html>
<html lang="zh_cn">
<head>
          <title>来玩魔王的咚</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charset="utf-8" />
        <!-- twitter card metadata -->
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="/images/mowang.png">
<meta name="twitter:site" content="">
<meta name="twitter:title" content="模拟系统负载">
<meta name="twitter:description" content="<p>手动提升CPU、内存、磁盘读写，触发告警</p>">
        <!-- OG Tags -->
<meta property="og:url" content="/overload-cpu-memory-for-test.html"/>
<meta property="og:title" content="来玩魔王的咚 | 模拟系统负载" />
<meta property="og:description" content="<p>手动提升CPU、内存、磁盘读写，触发告警</p>" />
        <!-- favicon -->
        <link rel="icon" type="image/png" href="/images/mowang.png">
        <!-- moment.js for date formatting -->
        <script src="/theme/js/moment.js"></script>
        <!-- css -->
        <link rel="stylesheet" type="text/css" href="/theme/css/main.css" />
        <!-- 左边的menu，如果页面高度不够，就跟着滚动，否则文章分类显示不全 -->
        <link rel="stylesheet" type="text/css" href="/theme/css/mycss/menu.css" />
		<script>
			
                /*! grunt-grunticon Stylesheet Loader - v2.1.2 | https://github.com/filamentgroup/grunticon | (c) 2015 Scott Jehl, Filament Group, Inc. | MIT license. */
    
    (function(e){function t(t,n,r,o){"use strict";function a(){for(var e,n=0;u.length>n;n++)u[n].href&&u[n].href.indexOf(t)>-1&&(e=!0);e?i.media=r||"all":setTimeout(a)}var i=e.document.createElement("link"),l=n||e.document.getElementsByTagName("script")[0],u=e.document.styleSheets;return i.rel="stylesheet",i.href=t,i.media="only x",i.onload=o||null,l.parentNode.insertBefore(i,l),a(),i}var n=function(r,o){"use strict";if(r&&3===r.length){var a=e.navigator,i=e.Image,l=!(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1")||e.opera&&-1===a.userAgent.indexOf("Chrome")||-1!==a.userAgent.indexOf("Series40")),u=new i;u.onerror=function(){n.method="png",n.href=r[2],t(r[2])},u.onload=function(){var e=1===u.width&&1===u.height,a=r[e&&l?0:e?1:2];n.method=e&&l?"svg":e?"datapng":"png",n.href=a,t(a,null,null,o)},u.src="",document.documentElement.className+=" grunticon"}};n.loadCSS=t,e.grunticon=n})(this);(function(e,t){"use strict";var n=t.document,r="grunticon:",o=function(e){if(n.attachEvent?"complete"===n.readyState:"loading"!==n.readyState)e();else{var t=!1;n.addEventListener("readystatechange",function(){t||(t=!0,e())},!1)}},a=function(e){return t.document.querySelector('link[href$="'+e+'"]')},c=function(e){var t,n,o,a,c,i,u={};if(t=e.sheet,!t)return u;n=t.cssRules?t.cssRules:t.rules;for(var l=0;n.length>l;l++)o=n[l].cssText,a=r+n[l].selectorText,c=o.split(");")[0].match(/US\-ASCII\,([^"']+)/),c&&c[1]&&(i=decodeURIComponent(c[1]),u[a]=i);return u},i=function(e){var t,o,a;o="data-grunticon-embed";for(var c in e)if(a=c.slice(r.length),t=n.querySelectorAll(a+"["+o+"]"),t.length)for(var i=0;t.length>i;i++)t[i].innerHTML=e[c],t[i].style.backgroundImage="none",t[i].removeAttribute(o);return t},u=function(t){"svg"===e.method&&o(function(){i(c(a(e.href))),"function"==typeof t&&t()})};e.embedIcons=i,e.getCSS=a,e.getIcons=c,e.ready=o,e.svgLoadedCallback=u,e.embedSVG=u})(grunticon,this);
                
                grunticon(["/theme/css/icons.data.svg.css", "/theme/css/icons.data.png.css", "/theme/css/icons.fallback.css"]);
            </script>
        <noscript><link href="/theme/css/icons.fallback.css" rel="stylesheet"></noscript>
        <!-- menu toggle javascript -->
        <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", initMenu);
            
            function initMenu(){
                var menu = document.getElementById("menu");
                var menulink = document.getElementById("menu-link");
                menulink.addEventListener("click", function toggleMenu(){
                        window.event.preventDefault();
                        menulink.classList.toggle('active');
                        menu.classList.toggle('active');              
                    });
            };
        </script>
        <!-- 不蒜子 -->
        <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

    <meta name="description" content="<p>手动提升CPU、内存、磁盘读写，触发告警</p>" />

    <meta name="tags" content="监控" />
  <!-- 替换部分base的样式，看文章时，要再宽一点，右边有很多空间可以撑开 -->
  <link rel="stylesheet" type="text/css" href="/theme/css/mycss/article.css" />

</head>
<body>
    <div role="banner" id="masthead">
        <header>
            <a href="/"><img src="/images/mowang.png" alt="McManus Logo"></a>
                <h1>来玩魔王的咚@骑士救兵</h1>
            <a href="#menu" id="menu-link">more stuff</a>
            <nav id="menu">
                <ul>
                        <li><a href="/tags">tags</a></li>
                            <li><a href="/category/cloud.html">Cloud</a></li>
                            <li><a href="/category/docker.html">Docker</a></li>
                            <li><a href="/category/go.html">Go</a></li>
                            <li class="active"><a href="/category/linux.html">Linux</a></li>
                            <li><a href="/category/python.html">Python</a></li>
                            <li><a href="/category/xue-xi-bi-ji.html">学习笔记</a></li>
                            <li><a href="/category/yun-wei-zi-dong-hua.html">运维自动化</a></li>
                </ul>
            </nav>
        </header>
    </div>
        <div class="page" role="main">
  <div class="article" role="article">
    <article>
        <footer>
            <a name="top"></a>
            <p>
              <time datetime=" 2022-02-18 15:52:00+08:00">
                <script>document.write(moment('2022-02-18 15:52:00+08:00').format('LL'));</script>
              </time>
              ~
              <time datetime=" 2022-02-18 15:52:00+08:00">
                <script>document.write(moment('2022-02-18 17:00:00+08:00').format('LL'));</script>
              </time>
            </p>
        </footer>
        <header>
          <h2>
            模拟系统负载
          </h2>
        </header>
      <div class="content">
         <div class="toc">
<ul>
<li><a href="#cpu">CPU</a><ul>
<li><a href="#wei-sui-ji-she-bei">伪随机设备</a></li>
</ul>
</li>
<li><a href="#wu-li-nei-cun">物理内存</a></li>
<li><a href="#ying-yong-nei-cun">应用内存</a></li>
<li><a href="#ci-pan-io">磁盘 I/O</a></li>
</ul>
</div>
<p>配置监控系统的时候，需要触发一些告警策略。降低阈值是一个方法，但是比较被动。通过一些手动来主动触发阈值用起来会更加灵活。  </p>
<h3 id="cpu"><a class="toclink" href="#cpu">CPU</a></h3>
<p>用gzip会提升CPU的负载，这里需要提供源源不断的数据让gzip一直处理:</p>
<div class="highlight"><pre><span></span><code>cat /dev/urandom <span class="p">|</span> gzip -9 &gt; /dev/null
</code></pre></div>

<p>可能CPU的负载还不够高，想要更高的负载，就不停的压缩、解压:</p>
<div class="highlight"><pre><span></span><code>cat /dev/urandom <span class="p">|</span> gzip -9 <span class="p">|</span> gzip -d &gt; /dev/null
<span class="c1"># 再多套几层，会有更高的负载</span>
cat /dev/urandom <span class="p">|</span> gzip -9 <span class="p">|</span> gzip -d <span class="p">|</span> gzip -9 <span class="p">|</span> gzip -d &gt; /dev/null
</code></pre></div>

<p>按下 CTRL+C 来终止进程，负载会降回来。  </p>
<h4 id="wei-sui-ji-she-bei"><a class="toclink" href="#wei-sui-ji-she-bei">伪随机设备</a></h4>
<p>/dev/random和/dev/urandom是Linux系统中提供的随机伪设备，这两个设备的任务，是提供永不为空的随机字节数据流。<br>
/dev/random的random pool依赖于系统中断，在系统的中断数不足时，会一直尝试读取进入等待状态。数据的随机性好，中间可能会停顿。<br>
/dev/urandom不依赖系统的中断，也就不会造成进程忙等待，但是数据的随机性也不高，不过数据流不会有停顿。<br>
用cat命令可以读取二进制流，但是没有可读性，可以再用od命令转为十六进制:</p>
<div class="highlight"><pre><span></span><code><span class="gp">$ </span>cat /dev/random <span class="p">|</span> od -x <span class="p">|</span> head -n <span class="m">10</span>
<span class="go">0000000 8841 6abe 9891 110f 3fae 6c95 235f 39a3</span>
<span class="go">0000020 362b 8c80 e44a 9a5b efbe e554 38f4 f177</span>
<span class="go">0000040 f661 19b1 c296 cf0c 616c 5979 bb9e b282</span>
<span class="go">0000060 69c8 1811 0c92 ea12 d599 53b0 efba d72a</span>
<span class="go">0000100 a473 1cf4 aad5 7442 8d63 a5c2 52a2 b9f2</span>
<span class="go">0000120 ff94 387a 7247 a503 4914 2719 7876 0011</span>
<span class="go">0000140 5fed 87a3 6136 0f9c 4d21 75d2 c51d 1e68</span>
<span class="go">0000160 d6fc 14e3 59a7 e869 f3f7 d989 bf44 a553</span>
<span class="go">0000200 a521 1f0f a929 9204 2093 313c 4e71 52e5</span>
<span class="go">0000220 fb47 3e1b 704c eeb8 4eb0 9fd0 a151 3912</span>
<span class="gp">$</span>
</code></pre></div>

<p>这里还加了head，在生成10行之后就会自动停止。  </p>
<h3 id="wu-li-nei-cun"><a class="toclink" href="#wu-li-nei-cun">物理内存</a></h3>
<p>内存还分物理内存和应用内存，推荐下面占用应用内存的方法。安全并且不要root权限。<br>
占用物理内存需要root权限，一般占用应用内存就可以了。另外提升内存占用会有风险，用满了<strong>会导致系统崩溃</strong>。崩溃后系统可能停止任何响应，需要手动重启，硬重启，慎用。<br>
首先创建一个挂载点，然后挂载ramfs文件系统:</p>
<div class="highlight"><pre><span></span><code>mkdir z
mount -t ramfs ramfs z/
</code></pre></div>

<p>然后，使用 dd 命令，在目录下创建文件，比如创建一个512M的文件，就是占用了512M的物理内存:</p>
<div class="highlight"><pre><span></span><code>dd <span class="k">if</span><span class="o">=</span>/dev/zero <span class="nv">of</span><span class="o">=</span>z/file <span class="nv">bs</span><span class="o">=</span>1M <span class="nv">count</span><span class="o">=</span><span class="m">512</span>
</code></pre></div>

<p>大小可以通过下面的参数来修改:</p>
<ul>
<li>bs 块大小，B（字节），K（KB），M（MB），G（GB）</li>
<li>count 块的数量</li>
</ul>
<p>下面都是表示1G:</p>
<div class="highlight"><pre><span></span><code>dd <span class="k">if</span><span class="o">=</span>/dev/zero <span class="nv">of</span><span class="o">=</span>z/file1 <span class="nv">bs</span><span class="o">=</span>1M <span class="nv">count</span><span class="o">=</span><span class="m">1024</span>
dd <span class="k">if</span><span class="o">=</span>/dev/zero <span class="nv">of</span><span class="o">=</span>z/file2 <span class="nv">bs</span><span class="o">=</span>1G <span class="nv">count</span><span class="o">=</span><span class="m">1</span>
</code></pre></div>

<p>可以用free命令立刻看到内存占用前后的变化:</p>
<div class="highlight"><pre><span></span><code><span class="gp">$ </span>free -h
<span class="go">              total        used        free      shared  buff/cache   available</span>
<span class="go">Mem:           3.7G        353M        3.1G        9.1M        261M        3.1G</span>
<span class="go">Swap:            0B          0B          0B</span>
<span class="gp">$ </span>free -h
<span class="go">              total        used        free      shared  buff/cache   available</span>
<span class="go">Mem:           3.7G        352M        2.1G        9.1M        1.3G        3.1G</span>
<span class="go">Swap:            0B          0B          0B</span>
<span class="gp">$ </span>free -h
<span class="go">              total        used        free      shared  buff/cache   available</span>
<span class="go">Mem:           3.7G        351M        1.1G        9.1M        2.3G        2.9G</span>
<span class="go">Swap:            0B          0B          0B</span>
<span class="gp">$ </span>
</code></pre></div>

<p>这是两次占用了1G物理内存前后的命令输出。可以看到used没有变，这个应该是应用内存。而buff/cache每次增加1G。  </p>
<h3 id="ying-yong-nei-cun"><a class="toclink" href="#ying-yong-nei-cun">应用内存</a></h3>
<p>这个方法比较安全，不需要root权限，也不会导致系统崩溃。<br>
这里用python来占用内存，python2也一样。直接开一个变量，往里存数据就好了。<br>
精确的做法是存二进制字符，1个字符是1字节（Byte），就是1B。进位是1024。<br>
直接用python shell就行了，下面的例子每次占用1G的内存:</p>
<div class="highlight"><pre><span></span><code>&gt;&gt;&gt; s1 = bytearray(1024 * 1024 * 1024)
&gt;&gt;&gt; s2 = bytearray(1024 * 1024 * 1024)
Killed
</code></pre></div>

<p>刚才占用的物理内存没有释放。所以第二次分配的时候应用程序终止了，应该是OOM。<br>
下面是free查看的结果:</p>
<div class="highlight"><pre><span></span><code><span class="gp">$ </span>free -h
<span class="go">              total        used        free      shared  buff/cache   available</span>
<span class="go">Mem:           3.7G        327M        1.3G        9.1M        2.1G        1.2G</span>
<span class="go">Swap:            0B          0B          0B</span>
<span class="gp">$ </span>free -h
<span class="go">              total        used        free      shared  buff/cache   available</span>
<span class="go">Mem:           3.7G        1.3G        278M        9.1M        2.1G        203M</span>
<span class="go">Swap:            0B          0B          0B</span>
<span class="gp">$ </span>
</code></pre></div>

<p>第一次是占用应用内存前，不过之前占用的物理内存没释放，可用空间不多了。<br>
第二次在可用空间仅278M的时候，还要使用1G空间，导致程序被系统中断了。  </p>
<h3 id="ci-pan-io"><a class="toclink" href="#ci-pan-io">磁盘 I/O</a></h3>
<p>磁盘I/O则是要不停的读写，先创建一个文件，然后不停的拷贝。<br>
用 dd 命令创建文件，内容用/dev/zero，创建全零的数据:</p>
<div class="highlight"><pre><span></span><code>dd <span class="k">if</span><span class="o">=</span>/dev/zero <span class="nv">of</span><span class="o">=</span>loadfile <span class="nv">bs</span><span class="o">=</span>1M <span class="nv">count</span><span class="o">=</span><span class="m">1024</span>
</code></pre></div>

<p>这里创建了一个1G的空白文件。<br>
然后是不停的拷贝文件:</p>
<div class="highlight"><pre><span></span><code><span class="c1"># 循环N次，然后结束</span>
<span class="k">for</span> i <span class="k">in</span> <span class="o">{</span><span class="m">1</span>..10<span class="o">}</span><span class="p">;</span> <span class="k">do</span> cp loadfile loadfile1<span class="p">;</span> <span class="k">done</span>
<span class="c1"># 无限循环，需要 CTRL+C 停止</span>
<span class="k">while</span> true<span class="p">;</span> <span class="k">do</span> cp loadfile loadfile1<span class="p">;</span> <span class="k">done</span>
</code></pre></div>

<p>这个动作同时还会飙升CPU，可以同时触发两个指标的阈值。  </p>
      </div>
      <div class="back-to-top">
        <a href="/">HOME</a>
        <a href="#top">TOP</a>
      </div>
    </article>
  </div>
<!-- end article -->
<!-- 页面往下滚动一段之后才会显示TOC -->
<script>
  window.onscroll = function() {
    var tocbox = document.getElementsByClassName('toc')[0];
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    var osWidth = document.documentElement.scrollWidth || document.body.scrollWidth;
    // console.log(osTop)
    if (osTop>300 && osWidth>865) {
      tocbox.style.display = "block"
    }
    if (osTop<300 || osWidth<865) {
      tocbox.style.display = "none"
    }
  }
</script>
                <footer>
                    <div class="icons">
                    </div>
                    <span id="busuanzi_container_page_pv" style="padding: 10px">本文阅读量<span id="busuanzi_value_page_pv"></span>次</span>
                    <span id="busuanzi_container_site_pv" style="padding: 10px">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
                    <span id="busuanzi_container_site_uv" style="padding: 10px">本站总访客数<span id="busuanzi_value_site_uv"></span>人</span>
                    <p>© <script>document.write(moment().format('YYYY'));</script> 749B</p>
                </footer>
        </div>
</body>
</html>